import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, Modal, message, Tooltip, Popconfirm } from 'antd';
import { InfoTipsC, NoQueryC, DATA_ENTRY, SeriesProductsC, TableC, FirstHeaderC, ContentPackage, PrimaryC } from '../../../comps';
import myStyle from './index.less';
import AddModalC from '../InitialSplit/addModal';
import ProductManageC from '../productManage';
import _ from 'lodash';
import uuid from 'es6-uuid';

@connect(({ seriesProductManageM, initialSplitM, userM: user, loading }) => ({
  seriesProductManageM,
  initialSplitM,
  user,
  loading,
}))
@Form.create()
export default class SeriesProductManageC extends PureComponent {
  state = {
    columns: undefined,
    currentPage: 1, //页码
    numInPage: 10, //每页条数
    pageInfo: {}, //后端返回的页码信息 拆分
    searchObj: {}, //查询条件
    isReset: false, //是否点击重置
    isQuery: false, //是否点击了查询
    addModalVisible: false, //新增系列产产品弹窗是否显示
    rowData: undefined, //当前点击表格行 系列产品
    columnsDefual: [
      { key: 'listCode', title: '系列产品代码' },
      { key: 'listName', title: '系列产品名称' },
      { key: 'stockSZ', title: '深交所股东号码' },
      { key: 'stockSH', title: '上交所股东号码' },
      { key: 'seatSH', title: '上交所席位号' },
      { key: 'seatSZ', title: '深交所席位号' },
      { key: 'createDate', title: '添加日期', type: 'date' },
    ],
    seriesInfo: undefined, //编辑的系列产品
  };
  componentDidMount() {
    if (this.props.isAll) this.queryTableList(); //查询系列产品列表
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}

  //查询系列产品列表
  queryTableList = () => {
    const { searchObj, isReset, numInPage, currentPage, rid } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }

    this.setState({
      columns: undefined,
      dataSource: undefined,
      pageInfo: {},
    }); //查询之前清除数据
    const params = {
      seriesProductId: searchObj?.seriesProductId || '',
      currentPage,
      numInPage,
    };
    this.props.dispatch({
      type: 'seriesProductManageM/queryTableList',
      payload: {
        ...params,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columns: _.cloneDeep(this.state.columnsDefual),
            dataSource: data.dataSource ? [...data.dataSource] : [],
            pageInfo: data.pageInfo || {},
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pageInfo: {},
          });
        }
      },
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };
  //拆分确认
  splitConfirm = (seriesProductId) => {
    if (!this.clickFlag) return;
    this.clickFlag = null;
    this.props.dispatch({
      type: 'initialSplitM/splitConfirm',
      payload: {
        listId: seriesProductId,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            message.success('拆分确认成功!');
            //刷新页面 ，重新请求
            this.setState(
              {
                rowData: undefined,
              },
              () => {
                this.queryTableList();
              },
            );
          } else message.error(res.msg || '拆分确认失败!');
        } else message.error('拆分确认失败!');
      },
    });
  };
  //删除系列id
  handleDeleteId = (seriesProductId) => {
    this.props.dispatch({
      type: 'initialSplitM/delBySeriesProudctId',
      payload: {
        seriesProductId,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            message.success('系列产品删除成功!');
            this.series.setSelect(undefined); //重新调用接口，获取系列产品下拉，不做任何定位；
            //刷新页面 ，重新请求
            this.setState(
              {
                rowData: undefined,
                searchObj: {},
              },
              () => {
                this.queryTableList();
              },
            );
          } else message.error(res.msg || '系列产品删除失败!');
        } else message.error('系列产品删除失败!');
      },
    });
  };

  //系列产品表格列表
  initTable = () => {
    const { currentPage, numInPage, columns, dataSource, pageInfo } = this.state;
    if (columns && columns.length && columns[columns.length - 1].key != 'operate') {
      columns.push({
        key: 'operate',
        type: 'operate',
        title: '操作',
        fixed: 'right',
        operates: [
          {
            title: '初始拆分',
            onClick: (record, index) => {
              this.props.getSeriesProductInfo(record, this.state.searchObj);
            },
          },
          {
            title: '编辑',
            onClick: (record, index) => {
              this.setState({ isAdd: false, addModalVisible: true, seriesInfo: record });
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.handleDeleteId(record.seriesProductId);
            },
          },
          {
            title: (
              <Popconfirm
                title={'确定拆分么？'}
                icon={<ExclamationCircleOutlined />}
                onConfirm={() => {
                  this.clickFlag = uuid(32);
                }} //为记录点击确认的操作，父组件onClick的时候进行判断
                onCancel={() => {
                  this.clickFlag = null;
                }}
              >
                <Tooltip title='拆分确认后，结果不可更改，只能系列删除'>拆分确认</Tooltip>
              </Popconfirm>
            ),
            onClick: (record, index) => {
              this.splitConfirm(record.seriesProductId);
            },
            rules: {
              disabled: { relation: 'or', items: [{ key: 'confirmed', value: ['1'], relation: ['='] }] },
            },
          },
        ],
      });
    }
    return (
      <div>
        <TableC
          columns={columns}
          dataSource={dataSource}
          onChange={this.handleTableChange}
          current={currentPage}
          total={pageInfo.total || 0}
          pageSize={numInPage}
          scroll={{ x: 'max-content' }}
          rowKey='key'
          onRow={(record) => {
            return {
              onDoubleClick: (event) => {
                this.setState({
                  rowData: record,
                });
              }, // 点击行
            };
          }}
          rowClassName={(record) => {
            return this.state.rowData && record.seriesProductId == this.state.rowData.seriesProductId ? myStyle.row_select : '';
          }}
        />
      </div>
    );
  };
  //新增系列产品成功
  addProductOk = (data) => {
    this.series.onDropdownVisibleChange(true, data);
    this.setState({
      //关闭模态框
      addModalVisible: false,
      seriesProductId: undefined,
      seriesInfo: undefined,
    });
  };
  render() {
    return (
      <ContentPackage
        title='系列产品管理'
        contentHtml={
          <div className={myStyle.seriesProductManage}>
            <div className={myStyle.topRow}>
              <div>
                <SeriesProductsC
                  dataIndex='seriesProductId'
                  title='系列产品'
                  form={this.props.form}
                  initialValue={this.props.isAll ? undefined : this.props.initSeriesId}
                  onChange={(e) => {
                    if (e) e.seriesProductId = e.value;
                    this.setState(
                      {
                        searchObj: e,
                        rowData: undefined,
                        currentPage: 1,
                      },
                      () => {
                        this.queryTableList();
                      },
                    );
                  }}
                  onRef={(e) => {
                    this.series = e;
                  }}
                />
              </div>
              <PrimaryC title={'新增'} onClick={() => this.setState({ isAdd: true, addModalVisible: true })} />
            </div>
            {this.initTable()}
            <InfoTipsC style={{ fontSize: '12px', height: '28px', padding: '0 10px', width: '100%' }} Left='双击系列产品列表的某一行，该行浅蓝色高亮，下方显示对应的子产品信息。' />
            {this.state.addModalVisible && (
              <AddModalC
                visible={this.state.addModalVisible}
                onCancel={() => this.setState({ addModalVisible: false, seriesInfo: undefined })}
                onOk={this.addProductOk}
                info={this.state.seriesInfo}
                type={this.state.isAdd == true ? 1 : 2}
              />
            )}
            <ProductManageC seriesProductId={this.state.rowData?.seriesProductId} listName={this.state.rowData?.listName} />
          </div>
        }
      />
    );
  }
}
